<template>
<!--  <el-dialog-->
<!--    :title="!dataForm.id ? '新增' : '修改'"-->
<!--    :close-on-click-modal="false"-->
<!--    :visible.sync="visible"-->
<!--  append-to-body>-->
  <div class="fillcontain" v-loading="loading">
    <div class="head-title"> <i class="el-icon-edit-outline">新增规则</i></div>
    <el-form :model="dataForm"  :rules="dataRule" ref="dataForm"
             @keyup.enter.native="dataFormSubmit()" label-width="80px" class="form-container">

      <el-row>
        <el-col :span="12">
          <el-form-item label="规则编码" label-width="120px" prop="ruleCode">
            <el-input v-model="dataForm.ruleCode" disabled placeholder="规则编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称" label-width="120px" prop="ruleName">
            <el-input v-model="dataForm.ruleName" placeholder="规则名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="12">
          <el-form-item label="所属规则组" label-width="120px" prop="groupIdentify">
            <el-select v-model="dataForm.groupIdentify" filterable placeholder="请选择">
              <el-option
                v-for="item in groupListData"
                :key="item.groupIdentify"
                :label="item.groupName"
                :value="item.groupIdentify"
                @click.native="changeGroup(item)">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否有效" label-width="120px" prop="isEffect">
            <el-switch
              v-model="dataForm.isEffect"
              active-color="#13ce66"
              inactive-color="#ff4949"
              on-value="1" on-text="是" off-text="否" off-value="0">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="规则描述" label-width="120px" prop="">
            <el-input type="textarea" :rows="3" v-model="dataForm.ruleDesc" placeholder="规则描述"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="mb10 pl20">
      <div class="content-title"><span>规则标识</span></div>
      <el-row class="mb10">
        <el-col :span="4">
          <el-button type="info" plain @click="addItem()">新增</el-button>
        </el-col>
      </el-row>

      <el-form ref="dataItemForm" :model="itemDataForm" label-width="80px">
        <el-table
          :data="itemDataForm.itemData"
          border
          style="width: 100%">
          <el-table-column
            prop="rulePropertyId"
            label="属性标识">
            <template slot-scope="scope">
              <el-form-item
                :rules="itemRule.rulePropertyId"
                :prop="'itemData.'+scope.$index+'.rulePropertyId'"
              >
                <el-select v-model="scope.row.rulePropertyId" filterable placeholder="请选择">
                  <el-option
                    v-for="item in ruleProperties"
                    :key="item.rulePropertyId"
                    :label="item.label"
                    :value="item.rulePropertyId"
                    @click.native="changeEntityItem(item,scope.row)">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="rulePropertyName"-->
<!--            label="属性名称"-->
<!--            width="180">-->
<!--            <template slot-scope="scope">-->
<!--              <el-form-item-->
<!--                :rules="itemRule.rulePropertyName"-->
<!--                :prop="'itemData.'+scope.$index+'.rulePropertyName'"-->
<!--              >-->
<!--                <el-input v-model="scope.row.rulePropertyName" disabled placeholder="属性名称"></el-input>-->
<!--              </el-form-item>-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column
            prop="rulePropertyValue"
            label="标识值">
            <template slot-scope="scope">
              <el-form-item class="tb-colum"
                            :rules="itemRule.rulePropertyValue"
                            :prop="'itemData.'+scope.$index+'.rulePropertyValue'">
                <el-date-picker
                  v-if="scope.row.rulePropertyId=='3' || scope.row.rulePropertyId=='4'"
                  v-model="scope.row.rulePropertyValue"
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>

                <el-input v-else v-model="scope.row.rulePropertyValue" placeholder="属性值"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small"
                         @click.native.prevent="deleteItem(scope.$index, itemDataForm.itemData)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <div class="mb10 pl20">
      <div class="content-title"><span>规则描述</span></div>
      <el-row style="margin-bottom: 10px;">
        <el-col :span="4">
          <el-button type="info" plain @click="addCondition()">添加条件</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="info" plain @click="addAction()">添加动作</el-button>
        </el-col>
      </el-row>

      <div class="rule_content">
        <el-row v-if="conditionList.length>0">
           <span class="txt1">如果</span>
        </el-row>
        <el-row v-else>
          <span class="txt1">如果</span>
          <el-row>
            <el-col :span="20">
              <span class="txt3">eval(true)</span>
            </el-col>
          </el-row>
        </el-row>
        <el-row v-for="(condition,cindex) in conditionList">
           <el-row v-if="cindex==0">
             <el-col :span="20">
              <span class="txt3">{{condition.conditionDesc}}</span>
             </el-col>
             <el-col :span="4">
               <i class="el-icon-edit" title="编辑"  @click="editCondition(condition,cindex)"></i>
               <i class="el-icon-delete" title="删除" @click="delCondition(condition,cindex)"></i>
             </el-col>
           </el-row>
           <el-row v-else-if="cindex!=0">
             <el-col :span="20">
               <span class="txt2">并且 </span> <span class="txt5">{{condition.conditionDesc}}</span>
             </el-col>
             <el-col :span="4">
               <i class="el-icon-edit" title="编辑"  @click="editCondition(condition,cindex)"></i>
               <i class="el-icon-delete" title="删除" @click="delCondition(condition,cindex)"></i>
             </el-col>
           </el-row>
        </el-row>
        <el-row v-if="actionList.length>0" >
          <span class="txt1">那么</span>
        </el-row>
        <el-row v-for="(action,aindex) in actionList">
          <el-row >
            <el-col :span="20">
              <span class="txt4">{{action.actionDesc}}</span>
            </el-col>
            <el-col :span="4">
              <i class="el-icon-edit" title="编辑"  @click="editAction(action,aindex)"></i>
              <i class="el-icon-delete" title="删除" @click="delAction(action,aindex)"></i>
            </el-col>
          </el-row>
        </el-row>
      </div>

    </div>

    <!-- 弹窗, 动作 -->
    <add-action v-if="addActionVisible" ref="addAction" :entityList="entityList" :chooseIndex="chooseActionIndex" :actionList="actionList" @refreshDataList="getActionDataList"></add-action>
    <!-- 弹窗, 条件 -->
    <add-condition v-if="addConditionVisible" ref="addCondition" :entityList="entityList" :chooseIndex="chooseIndex" :conditionList="conditionList" @refreshDataList="getConditionDataList"></add-condition>


    <div class="content-footer">
      <el-button type="info" plain @click="dataFormSubmit()">确定</el-button>
      <el-button @click="toList()">取消</el-button>
    </div>

  </div>
<!--  </el-dialog>-->
</template>

<script>
    import {saveData, getData,getGroupEntitys,copyData} from '@/api/ruleConfig/rule'
    import {listGroupData} from '@/api/ruleConfig/groupInfo'
    import {listPropertyData} from '@/api/baseConfig/property'
    import addAction from './add-action'
    import addCondition from './add-condition'
    import constant from "../../../../../api/constant";

    export default {
        data() {
            return {
                conditionList:[],
                actionList:[],
                delConditionList:[],
                delActionList:[],
                chooseIndex:0,
                chooseActionIndex:0,
                addActionVisible: false,
                addConditionVisible: false,
                groupListData: [],
                loading: false,
                visible: false,
                dataForm: {
                    id: 0,
                    groupIdentify: null,
                    ruleName: '',
                    ruleDesc: '',
                    ruleCode: '',
                    remark: '',
                    isEffect: '1'
                },
                entityList: [],
                ruleProperties: [],
                dataRule: {
                    ruleName: [
                        {required: true, message: '规则名称不能为空', trigger: 'blur'},
                        {  max: 50, message: '长度不能大于50', trigger: 'blur' }
                    ],
                    groupIdentify: [
                        {required: true, message: '所属规则组不能为空', trigger: 'change'}
                    ]
                },
                itemDataForm: {
                    itemData: []
                },
                itemRule: {
                    rulePropertyValue: [
                        {required: true, message: '属性值不能为空', trigger: 'blur'}
                    ],
                    rulePropertyId: [
                        {required: true, message: '规则属性不能为空', trigger: 'change'}
                    ]
                }
            }
        },
        created() {

        },
        components: {
            addAction,
            addCondition
        },
        mounted(){
            let id = this.$route.params.id
            let type = this.$route.params.type
            this.init(id,type)
        },
        methods: {
            toList(){
                constant.clearTag(this)
                this.$router.push({name: constant.routerName.listRule})
            },

            changeGroup(item){
                let params = {
                    groupIdentify: item.groupIdentify
                }
                getGroupEntitys(params).then(res=>{
                    this.entityList = res.data.data
                })
            },
            //删除条件
            delCondition(data,cindex){
                this.$confirm(`确定进行[删除]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.conditionList.splice(cindex, 1)
                    this.delConditionList.push(data)
                }).catch(() => {
                })

            },
            //修改条件
            editCondition(data,index){
                this.chooseIndex = index
                // console.log(index)
                this.addConditionVisible = true
                this.$nextTick(() => {
                    this.$refs.addCondition.init()
                })
            },
            //删除动作
            delAction(data,aindex){
                this.$confirm(`确定进行[删除]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.actionList.splice(aindex, 1)
                    this.delActionList.push(data)
                }).catch(() => {
                })

            },
            //修改动作
            editAction(data,index){
                this.chooseActionIndex = index
                // console.log(index)
                this.addActionVisible = true
                this.$nextTick(() => {
                    this.$refs.addAction.init()
                })
            },
            //刷新动作列表
            getActionDataList(data){
              this.actionList = data
            },
            //刷新条件列表
            getConditionDataList(data){
              this.conditionList = data
            },
            // 新增动作
            addAction() {
                if(!this.dataForm.groupIdentify){
                    this.$message.error('请选择规则组' )
                    return
                }
                this.chooseActionIndex = null
                this.addActionVisible = true
                this.$nextTick(() => {
                    this.$refs.addAction.init()
                })
            },
            // 新增条件
            addCondition() {
                if(!this.dataForm.groupIdentify){
                    this.$message.error('请选择规则组' )
                    return
                }
                this.chooseIndex = null
                this.addConditionVisible = true
                this.$nextTick(() => {
                    this.$refs.addCondition.init()
                })
            },

            init(id,type) {
                this.visible = true
                this.groupListData = []
                this.conditionList = []
                this.actionList = []
                this.delConditionList = []
                this.delActionList = []
                this.initGroup()

                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    if (id && id != "undefined") {
                        this.dataForm.id = id
                        if(type==='c'){//新增或修改
                            this.copyRule()
                        }else{//复制
                            this.getRule()
                        }
                    }
                })
            },
            getRule(){
                let params = {
                    ruleId: this.dataForm.id
                }
                this.$store.dispatch('loading/CHANGE_LOADING', true)
                getData(params).then(res => {
                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                    if (res.data.data && res.data.resultCode === 0) {
                        this.dataForm = res.data.data.rule
                        this.itemDataForm.itemData = res.data.data.relList
                        this.conditionList = res.data.data.conditionList
                        this.actionList = res.data.data.actionList
                        this.changeGroup(this.dataForm)
                    }
                }).catch(err=>{
                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                })
            },
            copyRule(){
                let params = {
                    ruleId: this.dataForm.id
                }
                this.$store.dispatch('loading/CHANGE_LOADING', true)
                copyData(params).then(res => {
                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                    if (res.data.data && res.data.resultCode === 0) {
                        this.dataForm = res.data.data.rule;
                        this.itemDataForm.itemData = res.data.data.relList
                        this.conditionList = res.data.data.conditionList
                        this.actionList = res.data.data.actionList
                        this.changeGroup(this.dataForm)
                    }
                }).catch(err=>{
                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                })
            },

            // 初始化规则组
            initGroup() {
                let params = {
                    is_effect: 1,
                    version_status:"1"
                }
                // 规则组
                listGroupData(params).then(res => {
                    this.groupListData = res.data.data
                })
                // 规则标识
                let params1 = {
                    is_effect: 1
                }
                listPropertyData(params1).then(res => {
                    this.ruleProperties = []
                    res.data.data.forEach(item=>{
                        item['label'] = item.rulePropertyName +'-'+ item.rulePropertyIdentify
                        this.ruleProperties.push(item)
                    })
                })
            },

            // 新增属性
            addItem() {
                let item = {
                    rulePropertyId: '',
                    rulePropertyValue: '',
                    rulePropertyName: ''
                }
                this.itemDataForm.itemData.push(item)
            },

            deleteItem(index, rows) {
                rows.splice(index, 1)
            },

            changeEntityItem(item, row) {
                let list = this.itemDataForm.itemData.filter(i => i.rulePropertyId === item.rulePropertyId)
                if (list && list.length > 1) {
                    row.rulePropertyId = ''
                    row.rulePropertyName = ''
                    this.$message.error('属性不能重复')
                }
                row.rulePropertyName = item.rulePropertyName
                if(row.rulePropertyId=='3' || row.rulePropertyId=='4'){
                    row.rulePropertyValue = ''
                }else if (item.defaultValue) {
                    row.rulePropertyValue = item.defaultValue
                }
            },

            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.$refs['dataItemForm'].validate((valid1) => {
                            if (valid1) {
                                if(this.itemDataForm.itemData.length<=0){
                                    this.$message.error("请添加规则标识")
                                    return
                                }
                                if(this.conditionList.length<=0 && this.actionList.length<=0){
                                    this.$message.error("请添加规则的条件和动作")
                                    return
                                }
                                // if(this.actionList.length<=0){
                                //     this.$message.error("请条件动作")
                                //     return
                                // }
                                let params = {
                                    rule: JSON.stringify(this.dataForm),
                                    relList: JSON.stringify(this.itemDataForm.itemData),
                                    conditionList: JSON.stringify(this.conditionList),
                                    actionList: JSON.stringify(this.actionList),
                                    delConditionList: JSON.stringify(this.delConditionList),
                                    delActionList: JSON.stringify(this.delActionList),
                                }
                                this.$store.dispatch('loading/CHANGE_LOADING', true)
                                saveData(params).then(res => {
                                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                                    if (res.data && res.data.resultCode === 0) {
                                        this.$message({
                                            message: '操作成功',
                                            type: 'success',
                                            duration: 1500,
                                            onClose: () => {
                                                this.visible = false
                                                this.dataForm = {
                                                    sceneId: null,
                                                    ruleName: '',
                                                    ruleDesc: '',
                                                    ruleEnabled: '1',
                                                    remark: '',
                                                    isEffect: '1'
                                                }
                                                this.itemDataForm.itemData = []
                                                // this.$emit('refreshDataList')
                                                this.toList()
                                            }
                                        })
                                    } else {
                                        this.$message.error(res.data.resultMsg)
                                    }
                                }).catch(err=>{
                                    this.$store.dispatch('loading/CHANGE_LOADING', false)
                                })
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style lang="less" scoped>
  .title {
    padding: 10px;
    background-color: rgba(248, 248, 248, 1);
    margin-bottom: 10px;
  }

  .el-table__row .el-form-item__content {
    margin-left: 0 !important;
  }

  .el-table__row .el-form-item {
    margin-bottom: 18px !important;
    margin-top: 18px !important;
  }
  .rule_content{
    border: 1px solid #606266;
    border-radius: 5px;
    padding: 10px;
    max-height: 200px;
    margin-right: 10px;
    min-height: 100px;
    overflow: auto;
  }
  .rule_content .txt1{

  }
  .rule_content .txt2{
    color: #F76565;
    display: inline-block;
  }
  .rule_content .txt3{
    color: #10AC8D;
    text-indent: 38px;
    display: inline-block;
  }
  .rule_content .txt5{
    color: #10AC8D;
    display: inline-block;
  }
  .rule_content .txt4{
    color: #4991DA;
    text-indent: 38px;
    display: block;
  }
</style>
